//
//  HDCFRiskTestVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/4.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFRiskTestVc.h"
#import "HDCFRiskTestCel.h"
#import "SVProgressHUD.h"
#import "HDCFRiskLevelVc.h"

#define LabelWidth screenWidth - 75
#define ButtonLabelWidth screenWidth - 130

@interface HDCFRiskTestVc ()<UITableViewDelegate, UITableViewDataSource, HDCFRiskTestCelDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataDictArray;
@property (nonatomic, strong) NSMutableDictionary *answerDict;

@end

@implementation HDCFRiskTestVc

- (void)setIsNormal:(BOOL)isNormal{
    _isNormal = isNormal;
}

- (NSMutableDictionary *)answerDict{
    if (!_answerDict) {
        self.answerDict = [NSMutableDictionary dictionary];
    }
    return _answerDict;
}

- (NSMutableArray *)dataDictArray{
    if (!_dataDictArray) {
        self.dataDictArray = [NSMutableArray array];
    }
    return _dataDictArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getQueationData];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationItem setTitle:@"风险测试"];
    CGRect tableFrame;
    if (_isNormal == YES) {
        tableFrame = CGRectMake(0, KNavHeight, screenWidth, screenHeight - KNavHeight - 49);
    }else{
       tableFrame = CGRectMake(0, 0, screenWidth, screenHeight - 49 - KNavHeight);
    }
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = ZKcolor(245, 245, 245);
    self.view.backgroundColor = ZKcolor(245, 245, 245);
    [self.view addSubview:tableView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn setBackgroundColor:ZKcolor(182, 27, 36)];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if (_isNormal == YES) {
         btn.frame = CGRectMake(0, screenHeight - 49, screenWidth, 49);
    }else{
         btn.frame = CGRectMake(0, screenHeight - 49 - KNavHeight, screenWidth, 49);
    }
   
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
}

- (void)getQueationData{
    [SVProgressHUD show];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[KparametTwo] = @"/public/investor/get-risk-test-subjects";
    [HttpRequest sendGetRequestWithURL:nil WithParamets:dict success:^(id result) {
        NSDictionary *dict = result[@"data"];
        [SVProgressHUD dismiss];
        for (int i = 0; i < dict.allKeys.count - 1; i++) {
            NSString *index = [NSString stringWithFormat:@"%d", i + 1];
            NSDictionary *question = dict[index];
            [self.dataDictArray addObject:question];
            
        }
        [self.tableView reloadData];
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

#pragma mark 确认提交

- (void)confirm{
    [SVProgressHUD show];
    NSArray *allKey = self.answerDict.allKeys;
    if (allKey.count < 12) {
        [SVProgressHUD showInfoWithStatus:@"请作答完毕"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }else{
        
        NSMutableDictionary *dictOne = [NSMutableDictionary dictionary];
        dictOne[@"accountNumber"] = kAcount;
        dictOne[@"answers"] = [self dictionaryToJson:self.answerDict];;
        
        NSString *jsonString = [self dictionaryToJson:dictOne];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[KparametTwo] = @"/public/investor/get-risk-appetite-result";
        dict[KparametOne] = jsonString;
        [HttpRequest sendGetRequestWithURL:nil WithParamets:dict success:^(id result) {
            if ([result[@"code"] isEqualToString:@"0000"]) {
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSDictionary *dict = result[@"data"];
                [user setValue:dict forKey:@"riskTest"];
                NSNumber *riskRating = dict[@"riskRating"];
                [user setValue:riskRating forKey:@"riskRating"];
                [user synchronize];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    HDCFRiskLevelVc *vc = [[HDCFRiskLevelVc alloc] init];
                    vc.riskLevel = riskRating.integerValue;
                    [self.navigationController pushViewController:vc animated:YES];
                });
                
                
            }else{
                [SVProgressHUD showInfoWithStatus:result[@"message"]];
                [SVProgressHUD dismissWithDelay:1.0];
            }
        } failure:^(NSError *errer) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            [SVProgressHUD dismissWithDelay:1.0];
        }];
    }
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *newString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return newString;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataDictArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellid";
    HDCFRiskTestCel *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [HDCFRiskTestCel HDCFRiskTestCel];
    }
    NSDictionary *dict = self.dataDictArray[indexPath.row];
    cell.dict = dict;
    NSString *indexStr = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
    NSArray *array = self.answerDict.allKeys;
    if ([array containsObject:indexStr]) {
        cell.isSelect = YES;
        cell.selectIndex = self.answerDict[indexStr];
        
    }else{
        cell.isSelect = NO;
        cell.selectIndex = @"e";
    }
    cell.delegate = self;
    cell.index = indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark cell的代理方法
- (void)returnTithQuestionTab:(NSString *)option WithIndex:(NSInteger)index{
    [self.answerDict setValue:option forKey:[NSString stringWithFormat:@"%ld", index + 1]];
//    [self.tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dict = self.dataDictArray[indexPath.row];
    CGFloat normalHeight = 14.32;
    CGFloat cellHeight;
    NSString *title = dict[@"title"];
    CGFloat titleHeight = [self sizeWithText:title font:[UIFont systemFontOfSize:14] maxW:LabelWidth];
    
    NSDictionary *optionDict = dict[@"option"];
    NSDictionary *optionA = optionDict[@"a"];
    CGFloat btnOneHeight = [self sizeWithText:optionA[@"content"] font:[UIFont systemFontOfSize:13] maxW:ButtonLabelWidth];
    btnOneHeight = btnOneHeight / normalHeight * 20;
    NSDictionary *optionB = optionDict[@"b"];
    CGFloat btnTwoHeight = [self sizeWithText:optionB[@"content"] font:[UIFont systemFontOfSize:13] maxW:ButtonLabelWidth];
    btnTwoHeight = btnTwoHeight / normalHeight * 20;
    NSDictionary *optionC = optionDict[@"c"];
    CGFloat btnThreeHeight = [self sizeWithText:optionC[@"content"] font:[UIFont systemFontOfSize:13] maxW:ButtonLabelWidth];
    btnThreeHeight = btnThreeHeight / normalHeight * 20;
    
    NSDictionary *optionD = optionDict[@"d"];
    CGFloat btnFourHeight = [self sizeWithText:optionD[@"content"] font:[UIFont systemFontOfSize:13] maxW:ButtonLabelWidth];
    btnFourHeight = btnFourHeight / normalHeight * 20;
    cellHeight = titleHeight + btnOneHeight + btnTwoHeight + btnThreeHeight + btnFourHeight + 121.5 + 20;
    return cellHeight;
}

//计算高度
- (CGFloat)sizeWithText:(NSString *)text font:(UIFont *)font maxW:(CGFloat)maxW
{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    
    return [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size.height;
}

@end
